import Autocomplete, { autocompleteClasses } from "@mui/material/Autocomplete";
import Box from "@mui/material/Box";
import Chip from "@mui/material/Chip";
import FormControl from "@mui/material/FormControl";
import Popper from "@mui/material/Popper";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import { styled, useTheme } from "@mui/material/styles";
import useMediaQuery from "@mui/material/useMediaQuery";
import * as React from "react";
import { ListChildComponentProps, VariableSizeList } from "react-window";

const LISTBOX_PADDING = 8; // px
const ITEM_HEIGHT = 48;
const ITEM_PADDING_TOP = 8;

function renderRow(props: ListChildComponentProps) {
  const { data, index, style } = props;
  const dataSet = data[index];
  const inlineStyle = {
    ...style,
    top: (style.top as number) + LISTBOX_PADDING,
  };

  return (
    <Typography
      component="li"
      {...dataSet[0]}
      noWrap
      style={inlineStyle}
      key={index}
    >
      {`${dataSet[2] + 1} - ${dataSet[1].replace("_", " ")}`}
    </Typography>
  );
}

const OuterElementContext = React.createContext({});

const OuterElementType = React.forwardRef<HTMLDivElement>((props, ref) => {
  const outerProps = React.useContext(OuterElementContext);
  return <div ref={ref} {...props} {...outerProps} />;
});

OuterElementType.displayName = "outerElement";

function useResetCache(data: any) {
  const ref = React.useRef<VariableSizeList>(null);
  React.useEffect(() => {
    if (ref.current != null) {
      ref.current.resetAfterIndex(0, true);
    }
  }, [data]);
  return ref;
}

const ListboxComponent = React.forwardRef<
  HTMLDivElement,
  React.HTMLAttributes<HTMLElement>
>(function ListboxComponent(props, ref) {
  const { children, ...other } = props;
  const itemData: React.ReactElement[] = [];
  (children as React.ReactElement[]).forEach(
    (item: React.ReactElement & { children?: React.ReactElement[] }) => {
      itemData.push(item);
      itemData.push(...(item.children || []));
    }
  );

  const theme = useTheme();
  const smUp = useMediaQuery(theme.breakpoints.up("sm"), {
    noSsr: true,
  });
  const itemCount = itemData.length;
  const itemSize = smUp ? 36 : 48;

  const getChildSize = (child: React.ReactElement) => {
    if (child.hasOwnProperty("group")) {
      return 48;
    }

    return itemSize;
  };

  const getHeight = () => {
    if (itemCount > 8) {
      return 8 * itemSize;
    }
    return itemData.map(getChildSize).reduce((a, b) => a + b, 0);
  };

  const gridRef = useResetCache(itemCount);

  return (
    <div ref={ref}>
      <OuterElementContext.Provider value={other}>
        <VariableSizeList
          itemData={itemData}
          height={getHeight() + 2 * LISTBOX_PADDING}
          width="100%"
          ref={gridRef}
          outerElementType={OuterElementType}
          innerElementType="ul"
          itemSize={(index) => getChildSize(itemData[index])}
          overscanCount={5}
          itemCount={itemCount}
        >
          {renderRow as any}
        </VariableSizeList>
      </OuterElementContext.Provider>
    </div>
  );
});
const StyledPopper = styled(Popper)({
  [`& .${autocompleteClasses.listbox}`]: {
    boxSizing: "border-box",
    "& ul": {
      padding: 0,
      margin: 0,
    },
  },
});
export default function MultipleSelectChip(props: any) {
  const { dataSource, placeHolder, setValue, value } = props;
  // const [personName, setPersonName] = React.useState<string[]>([]);
  return (
    <FormControl fullWidth sx={{ flex: "1" }}>
      <Autocomplete
        id="virtualize-demo"
        multiple
        value={value}
        disableListWrap
        autoComplete={true}
        PopperComponent={StyledPopper}
        ListboxComponent={ListboxComponent}
        options={dataSource}
        onChange={(event: any, newValue: string[] | null) => {
          if (!newValue) return;
          setValue(newValue);
          // setPersonName([...newValue]);
        }}
        onInputChange={(event, newInputValue) => {}}
        renderInput={(params) => <TextField {...params} label={placeHolder} />}
        renderOption={(props: any, option, state) => {
          return [props, option, state.index] as React.ReactNode;
        }}
        renderTags={(value: readonly string[], getTagProps) => (
          <Box
            sx={{
              display: "flex",
              flexWrap: "no-wrap",
              gap: 0.5,
              overflow: "auto",
              paddingBottom: "1rem",
            }}
          >
            {value.map((value) => (
              <Chip key={value} label={value.replace("_", " ")} />
            ))}
          </Box>
        )}
        renderGroup={(params) => params as any}
      />
    </FormControl>
  );
}
